package goodroommate.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import goodroommate.dal.DatabaseSession;
import goodroommate.dao.IComputingPlatformDao;
import goodroommate.dao.IKeyDataDao;
import goodroommate.dao.impl.ComputingPlatformDao;
import goodroommate.dao.impl.KeyDataDao;
import goodroommate.domain.KeyData;
import goodroommate.exception.DatabaseException;
import goodroommate.exception.RemoteCommunicationException;
import goodroommate.service.IComputingPlatformKmeansService;

public class ComputingPlatformKmeansService implements IComputingPlatformKmeansService {

	IComputingPlatformDao computingPlatformDao = new ComputingPlatformDao();

	IKeyDataDao keyDataDao = new KeyDataDao();

	public static final String TASK_USER_INFO_GROUPING = "gr-GroupUserInfo";

	public static final String KEY_GROUP_USER_INFO_STARTING_DATETIME = "computing.gr-GroupUserInfo.starttime.local";
	public static final String KEY_GROUP_USER_INFO_COMPLETE_DATETIME = "computing.gr-GroupUserInfo.completetime.local";

	@Override
	public boolean isUserInfoGroupingBusy(String apiRoot) throws RemoteCommunicationException {
		return computingPlatformDao.isTaskBusy(apiRoot, TASK_USER_INFO_GROUPING);
	}

	@Override
	public void startUserInfoGrouping(String apiRoot) throws RemoteCommunicationException {
		computingPlatformDao.startTask(apiRoot, TASK_USER_INFO_GROUPING);
	}

	@Override
	public Date getUserInfoGroupingStartDateTime() throws DatabaseException, ParseException {
		try (DatabaseSession dbSession = new DatabaseSession()) {
			KeyData keyData = keyDataDao.getKeyDataByName(dbSession, KEY_GROUP_USER_INFO_STARTING_DATETIME);
			if (keyData == null)
				return null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.parse(keyData.getValue());
		}
	}

	@Override
	public Date getUserInfoGroupingCompleteDateTime() throws DatabaseException, ParseException {
		try (DatabaseSession dbSession = new DatabaseSession()) {
			KeyData keyData = keyDataDao.getKeyDataByName(dbSession, KEY_GROUP_USER_INFO_COMPLETE_DATETIME);
			if (keyData == null)
				return null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.parse(keyData.getValue());
		}
	}
}
